<template>
  <NDrawer :show="visible" :width="600" :title="title" @update:show="emit('update:visible', $event)">
    <NDrawerContent>
      <NForm ref="formRef" :model="formData" :rules="formRules" label-placement="left" :label-width="100">
        <NFormItem label="资产名称" path="name">
          <NInput v-model:value="formData.name" placeholder="请输入资产名称" />
        </NFormItem>
        <NFormItem label="资产类型" path="assetType">
          <NSelect v-model:value="formData.assetType" :options="assetTypeOptions" placeholder="请选择资产类型" />
        </NFormItem>
        <NFormItem label="所属分类" path="categoryId">
          <NTreeSelect
            v-model:value="formData.categoryId"
            :options="categoryTreeOptions"
            placeholder="请选择所属分类"
            clearable
            :show-path="true"
            :filterable="true"
          />
        </NFormItem>
        <NFormItem label="分级标识" path="level">
          <NSelect v-model:value="formData.level" :options="assetLevelOptions" placeholder="请选择分级标识" />
        </NFormItem>
        <NFormItem label="状态" path="status">
          <NRadioGroup v-model:value="formData.status">
            <NRadio value="DRAFT">草稿</NRadio>
            <NRadio value="PUBLISHED">已发布</NRadio>
            <NRadio value="ARCHIVED">已归档</NRadio>
          </NRadioGroup>
        </NFormItem>
        <NFormItem label="来源类型" path="sourceType">
          <NInput v-model:value="formData.sourceType" placeholder="请输入来源类型" />
        </NFormItem>
        <NFormItem label="来源ID" path="sourceId">
          <NInputNumber v-model:value="formData.sourceId" placeholder="请输入来源ID" class="w-full" />
        </NFormItem>
        <NFormItem label="标签" path="tags">
          <NInput v-model:value="formData.tags" placeholder="请输入标签，多个标签用逗号分隔" />
        </NFormItem>
        <NFormItem label="描述" path="description">
          <NInput v-model:value="formData.description" type="textarea" placeholder="请输入描述" :rows="4" />
        </NFormItem>
        <NFormItem label="元数据" path="metadata">
          <NInput v-model:value="formData.metadata" type="textarea" placeholder="请输入元数据(JSON格式)" :rows="4" />
        </NFormItem>
        <NFormItem label="备注" path="remark">
          <NInput v-model:value="formData.remark" type="textarea" placeholder="请输入备注" :rows="3" />
        </NFormItem>
      </NForm>
      <template #footer>
        <NSpace justify="end">
          <NButton @click="handleClose">取消</NButton>
          <NButton type="primary" @click="handleSubmit">确定</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import type { FormInst, FormRules, TreeSelectOption } from 'naive-ui';
import type { DataAsset, AssetCategory } from '@/service/api/dataplatform/asset';
import { addDataAsset, updateDataAsset, AssetType, AssetLevel, AssetStatus } from '@/service/api/dataplatform/asset';

interface Props {
  visible: boolean;
  operateType: 'add' | 'edit';
  rowData: DataAsset | null;
  categoryTree: AssetCategory[];
}

const props = defineProps<Props>();
const emit = defineEmits<{
  'update:visible': [visible: boolean];
  success: [];
}>();

const formRef = ref<FormInst | null>(null);

const defaultFormData: DataAsset = {
  name: '',
  assetType: AssetType.TABLE,
  categoryId: undefined,
  level: AssetLevel.INTERNAL,
  status: AssetStatus.DRAFT,
  sourceType: '',
  sourceId: undefined,
  tags: '',
  description: '',
  metadata: '',
  remark: ''
};

const formData = ref<DataAsset>({ ...defaultFormData });

const formRules: FormRules = {
  name: [{ required: true, message: '请输入资产名称', trigger: 'blur' }],
  assetType: [{ required: true, message: '请选择资产类型', trigger: 'change' }]
};

const title = computed(() => (props.operateType === 'add' ? '新增资产' : '编辑资产'));

const assetTypeOptions = [
  { label: '数据表', value: AssetType.TABLE },
  { label: '视图', value: AssetType.VIEW },
  { label: 'API', value: AssetType.API },
  { label: '报表', value: AssetType.REPORT }
];

const assetLevelOptions = [
  { label: '公开', value: AssetLevel.PUBLIC },
  { label: '内部', value: AssetLevel.INTERNAL },
  { label: '机密', value: AssetLevel.CONFIDENTIAL },
  { label: '绝密', value: AssetLevel.SECRET }
];

// 转换分类树为TreeSelect选项
const categoryTreeOptions = computed(() => {
  if (!props.categoryTree || props.categoryTree.length === 0) {
    return [];
  }
  return convertToTreeSelectOptions(props.categoryTree);
});

function convertToTreeSelectOptions(categories: AssetCategory[]): TreeSelectOption[] {
  if (!categories) return [];
  return categories.map(category => ({
    label: category.name || '',
    value: category.id!,
    children: category.children && category.children.length > 0 
      ? convertToTreeSelectOptions(category.children) 
      : undefined
  }));
}

watch(
  () => props.visible,
  val => {
    if (val) {
      if (props.operateType === 'edit' && props.rowData) {
        formData.value = { ...props.rowData };
      } else {
        formData.value = { ...defaultFormData };
      }
    }
  }
);

function handleClose() {
  emit('update:visible', false);
}

async function handleSubmit() {
  await formRef.value?.validate();
  try {
    if (props.operateType === 'add') {
      await addDataAsset(formData.value);
      window.$message?.success('新增成功');
    } else {
      await updateDataAsset(formData.value);
      window.$message?.success('更新成功');
    }
    emit('success');
    handleClose();
  } catch (error) {
    window.$message?.error(props.operateType === 'add' ? '新增失败' : '更新失败');
  }
}
</script>
